# clear working environment
rm(list = ls())

# load packages
library(tidyverse)
library(patchwork)

# read data 
df <- read_rds("data/dem-transitions-replication-data.rds") %>%
  glimpse()

# create lagged polyarchy and executive constraints and transition indicator
df <- df %>%
  group_by(country) %>%
  mutate(poly_5 = dplyr::lag(v2x_polyarchy, 5)) %>%
  mutate(poly_4 = dplyr::lag(v2x_polyarchy, 4)) %>%
  mutate(poly_3 = dplyr::lag(v2x_polyarchy, 3)) %>%
  mutate(poly_2 = dplyr::lag(v2x_polyarchy, 2)) %>%
  mutate(poly_1 = dplyr::lag(v2x_polyarchy, 1)) %>%
  mutate(poly_t = v2x_polyarchy) %>%
  mutate(regime_5 = dplyr::lag(v2x_regime, 5)) %>%
  mutate(regime_4 = dplyr::lag(v2x_regime, 4)) %>%
  mutate(regime_3 = dplyr::lag(v2x_regime, 3)) %>%
  mutate(regime_2 = dplyr::lag(v2x_regime, 2)) %>%
  mutate(regime_1 = dplyr::lag(v2x_regime, 1)) %>%
  ungroup() %>%
  glimpse()

# create democratic transition indicator
df <- df %>%
  mutate(dem_transition = ifelse(v2x_regime > 1 & regime_1 <= 1, 1, 0)) %>%
  glimpse()

# keep only democratic transitions that occur from "clean" autocracy
df <- df %>%
  filter(dem_transition == 1 & regime_1 < 2 & regime_2 < 2 & regime_3 < 2 & regime_4 < 2 & regime_5 < 2) %>%
  select(country, year, dem_transition, v2x_regime, poly_5:poly_t) %>%
  mutate(transition_id = row_number()) %>%
  glimpse()

# pivot to longer format for plotting
df_long <- df %>%
  pivot_longer(cols = starts_with("poly"),
               names_to = "time",
               names_prefix = "poly_",
               values_to = "polyarchy",
               values_drop_na = FALSE) %>%
  mutate(time = case_when(time == "5" ~ "t-5",
                          time == "4" ~ "t-4",
                          time == "3" ~ "t-3",
                          time == "2" ~ "t-2",
                          time == "1" ~ "t-1",
                          time == "t" ~ "t")) %>%
  glimpse()

df_long$time <- factor(df_long$time, levels = c("t-5", "t-4", "t-3", "t-2", "t-1", "t"))

# group by time to transition 
df_group <- df_long %>%
  group_by(time) %>%
  dplyr::summarize(mean_poly = mean(polyarchy, na.rm = TRUE),
            sd_poly = sd(polyarchy, na.rm = TRUE),
            n_poly = n()) %>%
  mutate(se_poly = sd_poly/sqrt(n_poly),
         lo_ci = mean_poly - qt(1 - (.05 / 2), n_poly - 1) * se_poly,
         hi_ci = mean_poly + qt(1 - (.05 / 2), n_poly - 1) * se_poly) %>%
  glimpse()

# create Figure 2 in the main text
ggplot(data = df_long, aes(x = time, y = polyarchy)) +
  geom_line(alpha = .06, aes(group = transition_id)) +
  geom_line(inherit.aes = FALSE, data = df_group, aes(x = reorder(time, desc(time)), y = mean_poly, group = 1), color = "black", linewidth = .9) +
  geom_pointrange(inherit.aes = FALSE, data = df_group, aes(x = reorder(time, desc(time)), y = mean_poly, ymax = hi_ci, ymin = lo_ci), size = .12, linewidth = .7) +
  ylim(0, 1) +
  labs(y = "Polyarchy (V-Dem)",
       x = "Time to Democratic Transition") +
  theme(axis.text.x = element_text(color = "black", size = 10),
        axis.title.y = element_text(size = 12),
        legend.title = element_text(size = 12)) +
  theme_minimal()

# save plot
ggsave("figures/polyarchy-democratization-plot.pdf", width = 4.5, height = 3, units = "in", bg = "white")

# analyses referenced in the first para. of section "Changing Institutions and Preferences" in the main text
# is poly_5 different from poly_1
t.test(df$poly_5, df$poly_1)

# does countries' polyarchy score increase over time before transition?
df <- df %>%
  mutate(dem_increase = ifelse(poly_1 > poly_5, 1, 0)) %>%
  glimpse()
mean(df$dem_increase)
